package br.sc.senai.model.bd;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author jefferson_augusto
 */
public class Conexao {
    
    private static String endereco = "jdbc:mysql://localhost:3306/";
    private static String usuario = "root";
    private static String senha = "root";
    private static String driver = "com.mysql.jdbc.Driver";
    private static String nomeBanco = "";
    
    public static Boolean criarBanco(String pNomeBanco) throws SQLException{
        System.out.println("--- Começa a criar banco novo ---");
        Connection mConnection = null;
        try {
            nomeBanco = pNomeBanco;
            mConnection = DriverManager.getConnection("jdbc:mysql://localhost:3306/?user=root&password=" + senha);
            Statement mStatement = mConnection.createStatement();
            mStatement.executeUpdate("create database if not exists " + pNomeBanco);            
            System.out.println("--- Banco criado ---");
            
            return true;
        } catch (SQLException e) {
            throw e;
        } catch (Exception e) {
            throw new SQLException(e);
        } finally {
            try {
                if (mConnection != null || !mConnection.isClosed())
                    mConnection.close();
            } catch (SQLException ex) {
                throw ex;
            }
        }
    }
    
    public static Connection conecta() throws ClassNotFoundException, SQLException, Exception{
        Connection mConnection = null;
        try {
            Class.forName(driver);
            mConnection = DriverManager.getConnection(endereco + nomeBanco, usuario, senha);
            System.out.println("Conectou!");
        } catch (SQLException e) {
            throw e;
        } catch (ClassNotFoundException e){
            throw e;
        } catch (Exception e){
            throw new Exception("Erro ao conectar.", e);
        }
        return mConnection;
    }
    
    public static void desconectar(Connection pConnection) throws SQLException, Exception{
        try {
            if (!pConnection.isClosed())
                pConnection.close();
            System.out.println("Desconectou!");
        } catch (SQLException e) {
            throw e;
        } catch (Exception e){
            throw new Exception("Erro ao desconectar.", e);
        }
    }
}
